package com.lfs.service.impl;

import com.lfs.common.cache.redis.base.MapCache;
import com.lfs.common.constant.Constant;
import com.lfs.dao.AppManagerDao;
import com.lfs.model.vo.AgentAccess;
import com.lfs.service.AppManagerService;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class AppManagerServiceImpl implements AppManagerService {

    private static final Cache<String, AgentAccess> cache = CacheBuilder.newBuilder()
            .expireAfterAccess(12, TimeUnit.HOURS).maximumSize(1000).build();
    
    @Resource
    private AppManagerDao appManagerDao;

    @Resource
    private MapCache mapCache;

    @Override
    public AgentAccess queryAppKeyByAppId(String appId) {
        AgentAccess privateKey  =(AgentAccess)mapCache.hget(Constant.HASH_AGENT_APP_KEY+appId,Constant.HASH_AGENT_APP_KEY);
        // 2.redis不存在
        if (null ==privateKey) {
            // 从数据库获取
            privateKey = appManagerDao.queryAppKeyByAppId(appId);
            if(null != privateKey){
                // 存入数据库
                mapCache.hset(Constant.HASH_AGENT_APP_KEY+appId, Constant.HASH_AGENT_APP_KEY, privateKey);
            }
        }
        return privateKey;
    }
}
